package com.tionsy.springbootshiro.service;

import com.tionsy.springbootshiro.entity.UserEntity;
import com.tionsy.springbootshiro.entity.UserRoleEntity;
import com.tionsy.springbootshiro.repository.UserMapper;
import com.tionsy.springbootshiro.utils.PasswordHelper;
import com.tionsy.springbootshiro.utils.ShiroUtils;
import com.tionsy.springbootshiro.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author tiany
 * @date 2018/10/30 16:58
 */
@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public UserEntity getUserByUsername(String username){
        return  userMapper.getUserByUsername(username);
    }

    public UserEntity getUserById(String userId){
        return userMapper.getUserById(userId);
    }

    /**
     * 新增user
     * @param userEntity
     * @return
     */
    public int insertUser(UserEntity userEntity){
        UserEntity u=userMapper.getUserByUsername(userEntity.getUsername());
        if(u!=null){
            throw new RuntimeException("用户名已存在");
        }
        userEntity.setUserId(UUIDUtils.getUUID());
        userEntity.randomSalt();
//        userEntity.setCreateBy(ShiroUtils.getUser().getUsername());
        PasswordHelper.encryptPassword(userEntity);
        return userMapper.insertUser(userEntity);
    }

    /**
     * 获取所有user,可根据条件查询
     * @param username
     * @param email
     * @param phoneNumber
     * @return
     */
    public List<UserEntity> getAllUser(String username, String email, String phoneNumber){
        return userMapper.getAllUser(username,email,phoneNumber);
    }

    /**
     * 修改user
     * @param userEntity
     * @return
     */
    public int updateUser(UserEntity userEntity){
        UserEntity u=userMapper.getUserByUsername(userEntity.getUsername());
        if(u!=null){
            throw new RuntimeException("该用户名已存在");
        }
        userEntity.setUpdateBy(ShiroUtils.getUser().getUsername());
        return userMapper.updateUser(userEntity);
    }

    /**
     * 根据id批量删除user
     * @param ids user唯一标识集合
     * @return
     */
    public int deleteUserByIds(List<String> ids){
        return userMapper.deleteUserByIds(ids);
    }

    /**
     * 批量添加UserRole
     * @param userRoleEntities UserRole对象集合
     * @return
     */
    public int insertUserRoles(List<UserRoleEntity> userRoleEntities){
        return userMapper.insertUserRoles(userRoleEntities);
    }

    /**
     * 批量删除userRole，批量删除user时需要同时删除多个userRole
     * @param ids userId集合
     * @return
     */
    public int deleteUserRolesByUserIds(String[] ids){
        return userMapper.deleteUserRolesByUserIds(ids);
    }


    public void exportExcel(){
        List<UserEntity> userEntities =getAllUser(null,null,null);
    }
}

